from flask import current_app, jsonify
from flask import g
from flask import request

from info import constants
from info.models import News, Category
from info.modules.index import index_blue
from info.utils.common import get_login_info
from info.utils.response_code import RET

from flask import render_template


@index_blue.route('/')
@get_login_info
def index():
    user = g.user
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    categories = Category.query.all()

    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())
    data = {
        'user_info': user.to_dict() if user else None,
        'click_news_list': click_news_list,
        'categories': categories_list
    }

    return render_template('news/index.html', data=data)


@index_blue.route('/news_list')
def get_news_list():
    # 获取参数
    args_dict = request.args
    page = args_dict.get('page', 1)
    per_page = args_dict.get('per_page', constants.HOME_PAGE_MAX_NEWS)
    cid = args_dict.get('cid', '1')
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 查询
    # filters = [News.status==0]
    # # from sqlalchemy import and_
    # if cid != 1:
    #     filters.append(News.category_id == cid)
    filters = []
    # 引入逻辑and
    from sqlalchemy import and_
    if cid == 1:
        filters.append(News.status == 0)
    if cid != 1:
        filters.append(and_(News.category_id == cid, News.status == 0))

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')
    # 获取查询后的数据
    items = paginate.items
    # 获取总页码
    total_page = paginate.pages
    # 获取当前页码
    current_page = paginate.page
    news_list = []
    for news in items:
        news_list.append(news.to_basic_dict())
    data = {'news_list': news_list,
            'total_page': total_page,
            'current_page': current_page,
            }
    return jsonify(errno=RET.OK, errmsg='ok', data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
